package com.yx.study.leet.primary.tree;

import com.yx.study.leet.utils.TreeNode;

import java.util.Stack;

/**
 * 验证二叉搜索树--中序遍历
 * https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn08xg/
 * */
public class IsValidBST {
    public boolean isValidBST(TreeNode root) {
        if (root == null)
            return true;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (pre != null && root.val <= pre.val)
                return false;
            //保存前一个访问的结点
            pre = root;
            root = root.right;
        }
        return true;
    }
}
